package com.smforj.ssm.encrypt.des.impl;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.smforj.ssm.encrypt.des.EncryptDES;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/***
 * 简单加密与C# 通用
 * 
 * @author Haijun Gao 
 * @date 2017-1-14 下午2:25:52
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
public class EncryptDESImpl implements EncryptDES { 
	/***
	 * 注意:密钥必须为８位
	 */
	private static String dkey = "8SMFORJ6";  
	private final byte[] DESIV = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};// 设置向量
	
	private AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现 
	private static String charset = "utf-8";
	
	public EncryptDESImpl() throws Exception { 
	   iv = new IvParameterSpec(DESIV);// 设置向量 
	}   
	@Override 
	public String encode(String str) throws Exception { 
		return encode(str,dkey);
	}


	/****
	 * 
	 */ 
	public String encode(String str, String skey) throws Exception { 
	   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂 
	   DESKeySpec keySpec = new DESKeySpec(InspectKey(skey));// 设置密钥参数
	   Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象 
       Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
       enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
       byte[] pasByte = enCipher.doFinal(str.getBytes(charset));
       BASE64Encoder base64Encoder = new BASE64Encoder();
       return base64Encoder.encode(pasByte);
	}
	
	
	@Override
	public String decode(String str) throws Exception {
		return decode(str,dkey);
	}  
	public String decode(String str, String skey) throws Exception {
		   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂 
		   DESKeySpec keySpec = new DESKeySpec(InspectKey(skey));// 设置密钥参数
		   Key key = keyFactory.generateSecret(keySpec);// 得到密钥对象 
	       Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	       deCipher.init(Cipher.DECRYPT_MODE, key, iv);
	       BASE64Decoder base64Decoder = new BASE64Decoder();

	       byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(str));

	       return new String(pasByte, charset);
	}
	/***
	 * 
	 * @param skey 必须为8位非汉字，如果不正确则返回默认
	 * @return
	 * @throws UnsupportedEncodingException
	 * @date 2017-1-14 下午3:32:01
	 */
	private static byte[] InspectKey(String skey) throws UnsupportedEncodingException
	{
		if(isChinese(skey))
			return dkey.getBytes(charset); 
		return (skey.length() > 8) ? skey.substring(0,8).getBytes(charset) : dkey.getBytes(charset);
	}
	/***
	 * 根据Unicode编码完美的判断中文汉字和符号
	 * @param c
	 * @return
	 * @date 2017-1-14 下午3:17:23
	 */
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }
 
    /***
     * 完整的判断中文汉字和符号
     * @param strName
     * @return
     * @date 2017-1-14 下午3:17:29
     */
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

	
   public static void main(String[] args) {
       try {
           String test = "300833B2DDD9014000000003"+"北京金至科技股份有限公司";
           System.out.println(test.substring(0, 8));
           EncryptDESImpl des = new EncryptDESImpl();//自定义密钥
           System.out.println("加密前的字符："+test);
           String mstr = des.encode(test);
           System.out.println("加密后的字符："+mstr);
           System.out.println("解密后的字符："+des.decode(mstr));
       } catch (Exception e) {
           e.printStackTrace();
       }
   }  

}
